# Makefile for Template project

# 默认平台
PLATFORM ?= GENERIC

# 编译器
CC = gcc

# 编译选项
CFLAGS = -Wall -Wextra -std=c99 -g
CFLAGS += -D$(PLATFORM)_PLATFORM

# 目录定义
SRC_DIR = .
BUILD_DIR = Build
INC_DIRS = . DDL MDL

# 包含目录
INC_FLAGS := $(addprefix -I,$(INC_DIRS))

# 查找源文件（不包含 HAL）
C_SOURCES := $(wildcard *.c)
C_SOURCES += $(wildcard DDL/*/*.c)
C_SOURCES += $(wildcard MDL/*/*.c)

# 目标文件（保留目录结构）
OBJECTS = $(patsubst %.c,$(BUILD_DIR)/%.o,$(C_SOURCES))

# 目标可执行文件
TARGET = $(BUILD_DIR)/template_app.exe
STRESS_TEST_TARGET = $(BUILD_DIR)/stress_test.exe

# 默认目标
all: $(TARGET)

# 链接主应用程序
$(TARGET): $(OBJECTS)
	@if not exist "$(dir $@)" mkdir "$(dir $@)"
	$(CC) $(CFLAGS) -o $@ $^

# 链接压力测试程序（排除 main.o 和 HAL 文件）
$(STRESS_TEST_TARGET): $(filter-out $(BUILD_DIR)/main.o, $(filter-out $(BUILD_DIR)/HAL/%.o, $(OBJECTS))) $(BUILD_DIR)/stress_test.o
	@if not exist "$(dir $@)" mkdir "$(dir $@)"
	$(CC) $(CFLAGS) -o $@ $^

# 编译源文件（通用规则，保留目录结构）
$(BUILD_DIR)/%.o: %.c
	@if not exist "$(dir $@)" mkdir "$(dir $@)"
	$(CC) $(CFLAGS) $(INC_FLAGS) -c $< -o $@

# 编译压力测试源文件
$(BUILD_DIR)/stress_test.o: stress_test.c
	@if not exist "$(dir $@)" mkdir "$(dir $@)"
	$(CC) $(CFLAGS) $(INC_FLAGS) -c $< -o $@

# 创建Build目录
$(BUILD_DIR):
	@if not exist "$(BUILD_DIR)" mkdir "$(BUILD_DIR)"

# 清理
clean:
	@if exist "$(BUILD_DIR)" rmdir /s /q "$(BUILD_DIR)"

# 重新构建
rebuild: clean all

# 构建并运行压力测试
stress_test: $(STRESS_TEST_TARGET)
	$(STRESS_TEST_TARGET)

# 示例平台构建命令
stm32:
	$(MAKE) PLATFORM=STM32

gd32:
	$(MAKE) PLATFORM=GD32

generic:
	$(MAKE) PLATFORM=GENERIC

# PHONY targets
.PHONY: all clean rebuild stress_test stm32 gd32 generic